<!--
 * @Author: 杨光辉(GerhardYang)
 * @Date:2020-05-21 22:16:55
 * @LastEditors: 杨光辉(GerhardYang)
 * @LastEditTime: 2021-10-03 20:32:05
 * @Description: file content
 * @Copyright: 超图软件华中平台客户中心 (SuperMap Software Co., Ltd. -Central China Platform)
-->
<template>
  <div>
    <!-- 搜索框 -->
    <div id="searchbox">
      <!--提示页面-->
      <a-popover
        v-model="visible"
        :title="false"
        trigger="focus"
        placement="bottomLeft"
      >
        <div slot="content" style="width: 200px">
          <a-list :data-source="data" size="small">
            <a-list-item slot="renderItem" slot-scope="item">
              <div>
                <a @click="getRecomName(item[0])">{{ item[0] }}</a>
              </div>
            </a-list-item>
          </a-list>
        </div>
        <a-input-search
          v-model="inputStr"
          placeholder="请输入地址"
          @search="onSearch"
          @change="onChange"
          size="large"
          style="width: 300px; border-right: none"
          allowClear
        >
          <a-button slot="enterButton" style="border-radius: 0">
            <a-icon type="search" />
          </a-button>
        </a-input-search>
      </a-popover>
      <!-- 扩展按钮组 -->
      <a-button-group size="large" style="margin-left: 0px">
        <a-button
          title="路径规划"
          @click="openShowSearchpoi"
          style="border-radius: 0"
        >
          <icon-font type="icon-icon_lujingguihua" />
        </a-button>
        <a-button title="选择查询条件" @click="showClasses">
          <a-icon type="down" v-if="!isshowClasses" />
          <a-icon type="up" v-if="isshowClasses" />
        </a-button>
      </a-button-group>
      <p class="current-class-name-all">当前查询类型:{{ currentClass }}</p>
    </div>

    <div class="city-btn">
      <a-button size="large" @click="showCities" title="切换当前城市">
        {{ currentCity }}
        <a-icon type="down" v-if="isshowCities" />
        <a-icon type="up" v-if="!isshowCities" />
      </a-button>
    </div>
    <div class="city-all-pane">
      <Cities ref="Cities" />
    </div>
    <!-- 左侧展开面板 -->
    <div class="box-container">
      <Classes
        @selectedClass="onSelectedClass"
        ref="Classes"
        :key="classesKey"
        v-show="isshowClasses"
      />
      <NetworkAnalysis
        :isShowSearchpoi="isShowSearchpoi"
        ref="NetworkAnalysis"
        :key="networkAnalysisclassesKey"
      />
    </div>
    <SearchResult
      :isSearchByclass="isSearchByClass"
      ref="SearchResult"
      :key="searchResulKey"
    />
  </div>
</template>

<script>
import { esPost } from "../../services/ES/esQuery";
import queryMixins from "../../mixins/queryMixins";
import SearchResult from "./SearchResult";
import Classes from "./Classes/Classes";
import Cities from "./Cities";
import {
  dataGetFeaturesByGeometryParameters,
  dataGetFeaturesByGeometry,
} from "@/utils/http/iserverQuery";
import NetworkAnalysis from "./NetworkAnalysis";
// 自定义图标
import { Icon } from "ant-design-vue";
const IconFont = Icon.createFromIconfontCN({
  scriptUrl: "./iconfont/iconfont.js",
});
export default {
  data() {
    return {
      visible: false,
      inputStr: null,
      keyWordsArray: [],
      data: [],
      currentCity: "长沙",
      currentCityCode: "430100",
      searchResult: null, //单独图层属性
      searchResults: null, //每个图层属性
      isshowCities: true,
      isshowClasses: false,
      currentClass: "2020年报数据",
      isSearchByClass: false, //分类查询标识
      selected_Classes: null,
      searchGeometry: null,
      isShowSearchpoi: false,
      selectStrList: [],
      isQuery: false, //查询和模糊匹配标识
      noSelect: false,
      selectedoption: undefined,
      classesKey: 1,
      networkAnalysisclassesKey: 2,
      searchResulKey: 3,
      searchResulByClassKey: 4,
    };
  },
  components: {
    SearchResult,
    Cities,
    Classes,
    NetworkAnalysis,
    IconFont,
  },
  computed: {
    map() {
      return this.$store.state.map;
    },
    //查询图标图层
    markersFeatureGroup() {
      return this.$store.state.markersFeatureGroup;
    },
    //二次查询图标图层
    poiCircletFeatureGroup() {
      return this.$store.state.poiCircletFeatureGroup;
    },
    //选择的图层
    selected_layers() {
      return this.$store.state.checkedLayers;
    },
    //查询结果图层
    searchResultFeatureGroup() {
      return this.$store.state.searchResultFeatureGroup;
    },
    PoiLayer() {
      return this.$store.state.config.PoiLayer;
    },
    routeGroup() {
      return this.$store.state.routeGroup;
    },
  },
  mixins: [queryMixins],
  mounted() {
    let self = this;
    this.$eventBus.$on("clearAlldata", function () {
      self.forceRerender();
    });
    // 点击地图空白处关闭窗口;
    this.map.on("click", () => {
      this.visible = false;
    });
  },
  methods: {
    forceRerender() {
      this.$refs.Classes.visible = false;
      this.$refs.Classes.selectedClasses = [];
      this.networkAnalysisclassesKey += 1;
      this.searchResulKey += 1;
      this.visible = false;
      this.inputStr = null;
      this.keyWordsArray = [];
      this.data = [];
      this.searchResult = null; //单独图层属性
      this.searchResults = null; //每个图层属性
      this.isshowClasses = false;
      this.currentClass = "2020年报数据";
      this.isSearchByClass = false;
      this.selected_Classes = null; //选中的类别array
      this.isShowSearchpoi = false;
      this.selectStrList = [];
      this.isQuery = false;
      this.selectedoption = undefined;
      this.$refs.Cities.visiable = false;
      this.isshowCities = true;
    },
    openShowSearchpoi() {
      //关闭POI搜索结果
      this.$refs.SearchResult.onClose();
      this.isShowSearchpoi = true;
      this.isshowClasses = false;
      this.routeGroup.clearLayers();
    },
    selectone(index) {
      this.isQuery = true;
      if (index != "input") {
        if (this.selectStrList.length) {
          this.noSelect = false;
          let item = this.selectStrList[index];
          this.inputStr = item.properties[item.searchFiledName];
          this.selectedoption = index;
          this.onSearch(this.inputStr);
          return;
        }
      } else {
        this.onSearch(this.inputStr);
      }
    },
    regroupInEShits(arr, str) {
      var map = {},
        dest = [];
      arr.map((item) => {
        if (!map[item._source[str]]) {
          dest.push({
            name: item._source[str],
            data: [item],
          });
          map[item._source[str]] = item;
        } else {
          dest
            .filter((itemD) => itemD.name == item._source[str])[0]
            .data.push(item);
        }
      });
      return dest;
    },
    async getRecomNameData() {
      const groupStr = this.getGroupStr(this.currentCityCode, this.currentCity);
      const querydata = this.buildESqueryData(this.inputStr, groupStr, 0, 6);
      const querydataByCutWord = this.buildESqueryDataByCutWord(
        this.inputStr,
        groupStr,
        0,
        6
      );
      const esResByCutWord = await esPost(
        this.cutWordSearchURL,
        querydataByCutWord
      );
      const esRes = await esPost(this.defaultSearchURL, querydata);
      let doubleSearchits = esRes.hits.hits.concat(esResByCutWord.hits.hits);
      let afterReGroupList = this.regroupInEShits(doubleSearchits, "NAME");
      let hits = [];
      afterReGroupList.map((item) => {
        hits.push(item.data[0]);
      });
      if (hits.length > 0) {
        this.data = [];
        this.visible = true;
        for (let i = 0; i < 6; i++) {
          hits[i]
            ? this.data.push([hits[i]._source.NAME, hits[i]._source.ADDRESS])
            : "";
        }
      } else {
        this.data = [];
      }
    },
    getRecomName(item) {
      this.inputStr = item;
      this.data = [];
      this.visible = false;
      this.onSearch(item);
    },
    //回车开始查询
    startQueryPoi() {
      this.isQuery = true;
      this.onSearch(this.inputStr);
    },
    //响应类别选择组件
    onSelectedClass(item) {
      console.log("选中的查询类别", item);
      if (item && item.length) {
        this.isSearchByClass = true;
        this.selected_Classes = item;
      } else {
        this.isSearchByClass = false;
      }
    },
    showCities() {
      this.$refs.Cities.visiable = !this.$refs.Cities.visiable;
      if (!(this.$refs.Cities.visiable || !this.$refs.Cities.areaShow)) {
        this.$refs.Cities.areaShow = !this.$refs.Cities.areaShow;
      }

      this.isshowCities = !this.isshowCities;
    },
    showClasses() {
      this.isshowClasses = !this.isshowClasses;
      this.$refs.Classes.visiable = this.isshowClasses;
      if (this.isshowClasses) this.isShowSearchpoi = false;
    },
    //输入框监测
    onChange() {
      if (this.inputStr && !this.isSearchByClass) {
        //做一个输入值判断
        this.$refs.SearchResult.onClose();
        this.getRecomNameData();
      } else {
        this.visible = false;
        this.$refs.SearchResult.onClose();
      }
    },
    //除去字符串前后空格
    onSearch(inputStr) {
      if (inputStr) {
        this.visible = false;
        this.inputStr = this.inputStr.trim();
        this.MapQuery(inputStr);
      }
    },
    //分类查询入口
    async searchByclass(value, fromIndex, toIndex) {
      let features = [];
      //循环查询每一个类别
      for (let i = 0; i < this.selected_Classes.length; i++) {
        let dataUrl = this.selected_Classes[i].dadaUrl;
        if (!dataUrl || dataUrl === "") {
          this.$message.destroy();
          this.$message.warning(
            `暂无${this.selected_Classes[i].title}数据服务`
          );
          continue;
        }
        let params = await this.setParamsByClass(
          this.selected_Classes[i],
          value,
          fromIndex,
          toIndex
        );
        let result = await dataGetFeaturesByGeometry(dataUrl, params);
        if (this.dealresultByClass(result)) {
          this.selectStrList = result.features.features;
          result.features.features.map((item) => {
            item.searchFiledName = this.selected_Classes[i].searchFieldname;
          });

          features.push(result.features.features);
        }
        this.$refs.SearchResultByClass.pagination.total = result.totalCount; //设置分页总数
        this.$refs.SearchResultByClass.pagingQueryParameter = value; //传递参数，分页查询使用
      }
      // let params = await this.setParamsByClass(
      //   value,
      //   fromIndex,
      //   toIndex
      // );

      //if (this.isQuery) {
      features.length
        ? this.$refs.SearchResultByClass.buildResultData(features)
        : (this.$message.info("未查询到数据"),
          this.$refs.SearchResultByClass.onClose());
      //}
    },
    //设置查询参数
    async setParamsByClass(item, value, fromIndex, toIndex) {
      let sql = `${item.searchFieldname} like '%${value}%'`;
      let datasetNames = [`${item.datasource}:${item.dataset}`];
      let params;
      //查询或模糊匹配
      if (this.isQuery) {
        //因为没有区划编码，所以用空间查询
        params = await dataGetFeaturesByGeometryParameters(
          datasetNames,
          sql,
          this.searchGeometry
        );
      } else {
        let arrayfiles = [item.searchFieldname];
        let queryNum = 10;
        params = await dataGetFeaturesByGeometryParameters(
          datasetNames,
          sql,
          this.searchGeometry,
          arrayfiles,
          queryNum,
          fromIndex,
          toIndex
        );
      }
      return params;
    },
    //构建查询参数
    async MapQuery(value) {
      if (this.isSearchByClass) {
        this.$refs.SearchResultByClass.onClose();
        this.$refs.SearchResultByClass.listvisible = true;
        this.$refs.SearchResultByClass.inputStr = this.inputStr;
        this.$refs.SearchResultByClass.queryParams = [];
        this.$refs.SearchResultByClass.searchResults = [];
        this.$refs.SearchResultByClass.pagination.current = 1;
        this.searchResults = [];
        await this.searchByclass(value, 0, 10);
        return;
      } else {
        this.$refs.SearchResult.onClose();
        this.$refs.SearchResult.listvisible = true;
        this.$refs.SearchResult.inputStr = this.inputStr;
        this.$refs.SearchResult.queryParams = [];
        this.$refs.SearchResult.searchResults = [];
        this.$refs.SearchResult.pagination.current = 1;
        this.searchResults = [];

        const groupStr = this.getGroupStr(
          this.currentCityCode,
          this.currentCity
        );
        this.$refs.SearchResult.groupStr = groupStr;
        this.$refs.SearchResult.esURL = this.defaultSearchURL;
        this.$refs.SearchResult.getEShits();
      }
    },
    dealresultByClass(result) {
      if (!result) {
        this.$message.destroy();
        this.$message.error("服务/查询参数错误，请联系管理员");
        //this.$refs.SearchResult.onClose();
        return false;
      } else if (result.totalCount < 1) {
        this.$message.destroy();
        //this.$refs.SearchResult.onClose();
        return false;
      } else {
        return true;
      }
    },

    dealresult(result) {
      if (!result) {
        this.$message.destroy();
        this.$message.error("服务/查询参数错误，请联系管理员");
        this.$refs.SearchResult.onClose();
        return false;
      } else if (result.totalCount < 1) {
        this.$message.destroy();
        this.$message.warning("暂无数据");
        this.$refs.SearchResult.onClose();
        return false;
      } else {
        return true;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.box-container {
  position: absolute;
  top: 76px;
  left: 20px;
  z-index: 999;
  max-height: 82%;
  overflow: hidden;
  padding: 0px;
}
.city-all-pane {
  position: absolute;
  top: 76px;
  left: 370px;
  z-index: 999;
  max-height: 90%;
  padding: 0px;
  border-radius: 5px;
  opacity: 0.9;
  // box-shadow: darkgrey 0px 6px 10px 4px;
}
.city-btn {
  position: absolute;
  top: 27px;
  left: 430px;
  z-index: 99;
  padding: 0px;
  opacity: 1;
  .ant-btn-lg {
    height: 38px;
    padding: 0 15px;
    font-size: 16px;
  }
  // box-shadow: darkgrey 0px 1px 1px 1px;
}
#searchbox {
  display: flex;
  position: absolute;
  top: 26px;
  left: 20px;
  width: 400px;
  z-index: 9;
  // border-radius: 5px;
  // box-shadow: darkgrey 0px 1px 1px 1px;
  .address-search {
    border-left-width: 0px !important;
    /deep/.ant-select-selection--single {
      border-left: none;
    }
  }
  .current-class-name-all {
    width: auto;
    background-color: #fff;
    border: 1px solid #e8e8e8;
    border-radius: 0.2rem;
    display: none;
  }
}
</style>
